<template>
  <div class="activities-container">
    <div class="page-header">
      <h2>活动列表</h2>
    </div>

    <!-- 筛选表单 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchParams" class="activity-filter-form">
        <el-form-item label="活动名称">
          <el-input v-model="searchParams.keyword" placeholder="输入活动名称关键词" clearable></el-input>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="searchParams.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            clearable
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchParams.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            clearable
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="searchParams.status" placeholder="选择状态" clearable style="min-width: 90px;">
            <el-option label="已发布" value="1"></el-option>
            <el-option label="已取消" value="2"></el-option>
            <el-option label="已延期" value="3"></el-option>
            <el-option label="已结束" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="button-group">
            <el-button type="primary" @click="fetchActivities">查询</el-button>
            <el-button @click="resetSearchParams">重置</el-button>
            <el-button 
              type="info" 
              class="back-button"
              @click="goBack"
              :icon="ArrowLeft"
            >
              返回首页
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-empty v-if="activities.length === 0 && !loading" description="暂无活动" />
    <div v-else class="activities-grid" v-loading="loading">
      <el-card v-for="activity in activities" :key="activity.id" class="activity-card">
        <img
          :src="activity.coverUrl"
          class="activity-cover"
          alt="活动封面"
          @error="handleImageError"
        >
        <div class="activity-info">
          <h3>{{ activity.title }}</h3>
          <p class="description">{{ activity.description }}</p>
          <p>开始时间：{{ activity.startTime }}</p>
          <p>结束时间：{{ activity.endTime }}</p>
          <p>最大参与人数：{{ activity.maxParticipants }}人</p>
          <p>当前报名人数：{{ activity.numberApplicants }}人</p>
          <div class="activity-footer">
            <el-tag :type="getActivityStatusType(activity.status)">
              {{ getActivityStatusText(activity.status) }}
            </el-tag>
            <el-button
              type="primary"
              size="small"
              @click="handleSignUp(activity.id)"
              :disabled="activity.status !== '1'"
            >
              报名活动
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="showCommentsDialog(activity.id)"
            >
              查看评论
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 活动评论对话框 -->
    <el-dialog
      v-model="commentDialogVisible"
      title="活动评论"
      width="60%"
      draggable
      @close="resetCommentState"
    >
      <div class="comments-section">
        <!-- 评论列表 -->
        <div class="comment-list" v-loading="commentsLoading">
          <div v-if="activityComments.length === 0 && !commentsLoading">暂无评论</div>
          <!-- 渲染根评论 -->
          <RecursiveComment
            v-for="comment in activityComments"
            :key="comment.id"
            :comment="comment"
            :level="0"
            @submit-reply="handleNestedReply"
          />
        </div>
        
        <!-- 评论输入区 -->
        <div class="comment-input-area">
          <el-input
            v-model="newCommentContent"
            placeholder="写下你的评论..."
            type="textarea"
            :rows="3"
          ></el-input>
          <div class="comment-submit-button">
            <el-button type="primary" @click="submitComment" :disabled="!newCommentContent.trim()">发表评论</el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commentDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue';
import { clubApi } from '../api';
import { ElMessage } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import defaultCover from '../assets/default-club-cover.jpg';
import { useRouter } from 'vue-router';
import api from '../api'; // 确保导入了api实例
import RecursiveComment from '../components/RecursiveComment.vue'; // 导入 RecursiveComment 组件

const router = useRouter();

// 返回首页
const goBack = () => {
  router.push('/home');
};

const activities = ref([]);
const loading = ref(false);

// 筛选参数
const searchParams = reactive({
  keyword: null,
  startTime: null,
  endTime: null,
  status: null,
});

// --- 新增：活动评论相关状态 --- start
const commentDialogVisible = ref(false); // 控制评论对话框的显示
const currentActivityId = ref(null); // 当前查看评论的活动ID
const activityComments = ref([]); // 当前活动的评论列表 (树形结构)
const newCommentContent = ref(''); // 新评论的内容
const replyingToComment = ref(null); // 当前回复的评论对象，null 表示回复活动本身
const commentsLoading = ref(false); // 评论加载状态
const activityAuthorId = ref(null); // 新增：当前活动作者的ID
// --- 新增：活动评论相关状态 --- end

// --- 新增：递归评论组件 --- start
const CommentItem = { /* 定义为局部组件 */
  props: {
    comment: Object, // 当前评论对象
    level: { // 评论层级，用于控制缩进
      type: Number,
      default: 0
    }
  },
  emits: ['reply'], // 声明触发的事件
  template: `
    <div class="comment-item" :style="{ marginLeft: level * 20 + 'px' }" :class="{'nested-reply': level > 0}"> /* 根据层级增加左外边距，并添加 class */
      <div class="comment-header">
        <el-avatar :size="30" :src="comment.avatarUrl || 'https://cube.elemecdn.com/0/88/03b0d4db2da353509667cd25e8cd.jpg'" class="comment-avatar"></el-avatar>
        <div class="comment-header-info">
          <strong>{{ comment.username }}</strong>
          <span>{{ comment.createdAt }}</span>
        </div>
      </div>
      <div class="comment-content">{{ comment.content }}</div>
      <div class="comment-actions">
        <el-button type="text" size="small" @click="$emit('reply', comment)">回复</el-button>
      </div>
      <!-- 递归渲染子回复 -->
      <div v-if="comment.replies && comment.replies.length > 0" class="comment-replies">
        <CommentItem
          v-for="reply in comment.replies"
          :key="reply.id"
          :comment="reply"
          :level="level + 1"
          @reply="$emit('reply', $event)"
        />
      </div>
    </div>
  `,
};
// --- 新增：递归评论组件 --- end

const fetchActivities = async () => {
  loading.value = true;
  try {
    // 从 localStorage 获取 Home.vue 中设置的初始搜索参数（可选，如果 Home.vue 传递了默认参数）
    // 优先使用当前页面的 searchParams
    const initialSearchParams = JSON.parse(localStorage.getItem('activitySearchParams')) || {};
    
    // 合并初始参数和当前筛选参数，当前筛选参数优先
    const mergedSearchParams = { ...initialSearchParams, ...searchParams };

    const response = await clubApi.getAllActivities(mergedSearchParams); // 调用获取所有活动的接口
    if (response.code === 200) {
      activities.value = response.data; 
    } else {
      ElMessage.error(response.message || '获取活动列表失败');
    }
  } catch (error) {
    console.error('获取活动列表失败:', error);
    ElMessage.error('获取活动列表失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选条件
const resetSearchParams = () => {
  searchParams.keyword = '';
  searchParams.startTime = null; // 重置开始时间
  searchParams.endTime = null;   // 重置结束时间
  searchParams.status = null;
  // 重置后重新加载活动列表
  fetchActivities();
};

// 处理图片加载失败
const handleImageError = (e) => {
  e.target.src = defaultCover; // 使用导入的默认封面图
};

// 活动状态映射
const getActivityStatusType = (status) => {
  const statusMap = {
    '0': 'info',    // 未发布
    '1': 'success', // 已发布
    '2': 'danger',  // 已取消
    '3': 'warning',  // 已延期
    '4': 'info'     // 已结束 - Using 'info' type, adjust as needed
  };
  return statusMap[status] || 'info';
};

const getActivityStatusText = (status) => {
  const statusMap = {
    '0': '未发布',
    '1': '已发布',
    '2': '已取消',
    '3': '已延期',
    '4': '已结束' // Add text for status 4
  };
  return statusMap[status] || '未知状态';
};

// 处理活动报名 (从 MyClubs.vue 复用，稍作修改)
const handleSignUp = async (activityId) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    if (!userInfo || !userInfo.id) {
      ElMessage.error('获取用户信息失败');
      return;
    }

    const response = await clubApi.signUpActivity(activityId, userInfo.id);
    if (response.code === 200) {
      ElMessage.success('报名成功');
      // 报名成功后可以考虑刷新当前活动的状态或重新加载列表
      // 为了简单起见，这里重新加载整个活动列表
      fetchActivities();
    } else {
      ElMessage.error(response.message || '报名失败');
    }
  } catch (error) {
    console.error('报名失败:', error);
    ElMessage.error('报名失败');
  }
};

// --- 新增：活动评论相关方法 --- start

// 显示评论对话框并加载评论
const showCommentsDialog = async (activityId) => {
  currentActivityId.value = activityId;
  commentDialogVisible.value = true;
  // 获取活动作者ID
  try {
    const authorResponse = await api.get(`/userclubs/comments/author/${activityId}`);
    if (authorResponse.code === 200 && authorResponse.data !== null) {
      activityAuthorId.value = authorResponse.data;
      console.log('Activity author ID:', activityAuthorId.value); // 调试日志
    } else {
      activityAuthorId.value = null; // 获取失败或作者不存在则设为 null
      console.warn('Failed to get activity author ID or author not found:', authorResponse.message);
    }
  } catch (error) {
    activityAuthorId.value = null; // 获取作者ID出错
    console.error('Error fetching activity author ID:', error);
    ElMessage.error('获取活动作者信息失败');
  } finally {
    // 无论是否成功获取作者ID，都加载评论
    fetchActivityComments(activityId, activityAuthorId.value); // 将作者ID传递给获取评论函数
  }
};

// 获取活动评论 (使用真实后端接口)
const fetchActivityComments = async (activityId, authorId) => {
  commentsLoading.value = true; // 设置加载状态
  try {
    // 调用后端接口获取评论列表
    const response = await api.get(`/userclubs/comments/${activityId}`); // 使用您提供的接口地址和方法
    if (response.code === 200) {
      // 后端已返回树形结构，直接赋值
      // 遍历评论树，标记作者评论
      const markAuthorComments = (comments, authorId) => {
        if (!comments || !Array.isArray(comments)) return [];
        return comments.map(comment => {
          const isAuthor = authorId !== null && comment.userId === authorId;
          return {
            ...comment,
            isAuthor: isAuthor,
            replies: markAuthorComments(comment.replies, authorId) // 递归处理回复
          };
        });
      };
      activityComments.value = markAuthorComments(response.data, authorId);
    } else {
      console.error('获取评论失败:', response.message);
      ElMessage.error(response.message || '获取评论失败');
      activityComments.value = []; // 获取失败时清空评论列表
    }
  } catch (error) {
    console.error('获取评论失败:', error);
    ElMessage.error('获取评论网络错误');
    activityComments.value = []; // 获取失败时清空评论列表
  } finally {
    commentsLoading.value = false; // 结束加载状态
  }
};

// 提交评论或回复 (暂时使用前端模拟，待后端接口)
const submitComment = async () => {
  if (!newCommentContent.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }

  const userInfo = JSON.parse(localStorage.getItem('userInfo'));
  if (!userInfo || !userInfo.id) {
    ElMessage.error('请先登录');
    return;
  }

  // 调用后端接口提交顶层评论
  try {
    const payload = {
      activityId: currentActivityId.value,
      content: newCommentContent.value.trim(),
      parentId: null, // 顶层评论的 parentId 为 null
      replierId: userInfo.id
    };
    const response = await api.post('/activities/comments', payload); // 假设顶层评论提交接口是 /activities/comments
    if (response.code === 200) {
      ElMessage.success('评论发布成功');
      newCommentContent.value = '';
      // 重新加载评论列表以显示新评论
      fetchActivityComments(currentActivityId.value, activityAuthorId.value);
    } else {
      ElMessage.error(response.message || '评论发布失败');
    }
  } catch (error) {
    console.error('发布评论失败:', error);
    ElMessage.error('发布评论网络错误');
  }
};

// 处理嵌套回复
const handleNestedReply = async (parentId, content) => {
  if (!content.trim()) {
    ElMessage.warning('回复内容不能为空');
    return;
  }

  const userInfo = JSON.parse(localStorage.getItem('userInfo'));
  if (!userInfo || !userInfo.id) {
    ElMessage.error('请先登录');
    return;
  }

  try {
    const payload = {
      activityId: currentActivityId.value,
      content: content.trim(),
      parentId: parentId, // 回复的 parentId
      replierId: userInfo.id
    };
    const response = await api.post('/activities/comments', payload); // 假设回复提交接口是 /activities/comments
    if (response.code === 200) {
      ElMessage.success('回复发布成功');
      // 重新加载评论列表以显示新回复
      fetchActivityComments(currentActivityId.value, activityAuthorId.value);
    } else {
      ElMessage.error(response.message || '回复发布失败');
    }
  } catch (error) {
    console.error('发布回复失败:', error);
    ElMessage.error('发布回复网络错误');
  }
};

// 重置评论相关状态（对话框关闭时调用）
const resetCommentState = () => {
  currentActivityId.value = null;
  activityComments.value = [];
  newCommentContent.value = '';
  replyingToComment.value = null;
};

// --- 新增：活动评论相关方法 --- end

onMounted(() => {
  // 在组件挂载时检查是否有从 Home.vue 传递过来的筛选参数，并应用
  const initialSearchParams = JSON.parse(localStorage.getItem('activitySearchParams')) || {};
  // 清除 localStorage 中的参数，避免影响下次进入
  localStorage.removeItem('activitySearchParams');

  // 应用初始参数
  Object.assign(searchParams, initialSearchParams);

  // 如果初始参数包含时间范围，可能需要特殊处理，这里假设 Home.vue 只传递了 keyword, status 等
  // 如果 Home.vue 可能传递 startTime 和 endTime，需要确保这里的 searchParams reactive 对象能正确处理
  // 由于 Home.vue 传递的是 null，这里直接合并是安全的

  fetchActivities(); // 组件加载时根据初始或默认筛选条件获取活动列表
});
</script>

<style scoped>
.activities-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f7fafc 0%, #e3f6f5 100%);
  padding: 32px 0 40px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 28px;
}
.page-header h2 {
  font-size: 26px;
  font-weight: bold;
  color: #22577a;
  letter-spacing: 2px;
}

.filter-card {
  max-width: 1100px;
  margin: 0 auto 28px auto;
  border-radius: 16px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  border: 1.5px solid #e3e8ee;
  background: #fff;
}

.activity-filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 18px 0;
  padding: 18px 0 0 0;
  justify-content: center;
}
.activity-filter-form .el-form-item {
  margin-right: 24px;
  margin-bottom: 16px;
}
.button-group {
  display: flex;
  align-items: center;
  gap: 15px;
}
.back-button {
  margin-left: 10px;
  transition: all 0.3s;
  background-color: #909399;
  border-color: #909399;
}
.back-button:hover {
  transform: translateX(-5px);
  background-color: #a6a9ad;
  border-color: #a6a9ad;
}

.activities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 28px;
  max-width: 1200px;
  margin: 0 auto;
}
.activity-card {
  border-radius: 16px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  transition: transform 0.3s, box-shadow 0.3s;
  background: #fff;
  border: 1.5px solid #e3e8ee;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.activity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 32px 0 rgba(100, 200, 180, 0.18);
}
.activity-cover {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 12px 12px 0 0;
  margin-bottom: 10px;
}
.activity-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 18px 18px 10px 18px;
}
.activity-info h3 {
  margin-top: 0;
  margin-bottom: 5px;
  font-size: 18px;
  color: #333;
}
.activity-info p {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}
.description {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 10px;
}
.activity-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}
.el-tag {
  border-radius: 6px;
  padding: 0 10px;
  height: 26px;
  line-height: 26px;
  font-size: 14px;
}
.el-button {
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 500;
  font-size: 15px;
  transition: all 0.3s;
}
.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(100, 200, 180, 0.12);
}
.el-button--primary {
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%);
  border: none;
  color: #22577a;
}
.el-button--primary:hover {
  background: linear-gradient(90deg, #b8e1dd 0%, #8fd6e1 100%);
  color: #38a3a5;
}
.el-button--info {
  background: linear-gradient(90deg, #bfc6d1 0%, #e0e4ea 100%);
  border: none;
  color: #555;
}
.el-button--info:hover {
  background: linear-gradient(90deg, #e0e4ea 0%, #bfc6d1 100%);
  color: #333;
}
.el-empty {
  margin: 60px auto;
}
::-webkit-scrollbar {
  width: 8px;
  background: #e3f6f5;
}
::-webkit-scrollbar-thumb {
  background: #b8e1dd;
  border-radius: 4px;
}

/* --- 活动评论样式 --- start */
.comments-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-list {
  max-height: 400px; /* 设置最大高度并启用滚动条 */
  overflow-y: auto;
  padding-right: 10px; /* 避免滚动条遮挡内容 */
  padding-bottom: 20px; /* 增加底部填充 */
}

.comment-item {
  border: 1px solid #ebeef5; /* 增加边框 */
  border-radius: 8px; /* 圆角 */
  padding: 15px; /* 调整内边距 */
  margin-bottom: 15px; /* 底部外边距 */
  background-color: #fff; /* 背景颜色 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05); /* 阴影 */
  transition: all 0.3s ease; /* 过渡效果 */
}

.comment-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1); /* 鼠标悬停阴影效果 */
}

.comment-item.nested-reply {
  border-left: 3px solid #409eff; /* 回复评论左侧增加颜色条 */
  background-color: #f0f9eb; /* 回复评论背景颜色 */
}

.comment-header {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 10px; /* 增加底部外边距 */
  font-size: 14px;
  color: #606266;
}

.comment-avatar {
  margin-right: 10px; /* 头像右侧间距 */
  flex-shrink: 0; /* 防止头像被压缩 */
}

.comment-header-info {
  display: flex;
  flex-direction: column; /* 用户名和时间垂直排列 */
  font-size: 13px;
}

.comment-header strong {
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px; /* 用户名和时间戳之间的间距 */
}

.comment-header span {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  font-size: 15px;
  color: #303133;
  line-height: 1.6;
  margin-bottom: 10px; /* 评论内容和操作按钮之间的间距 */
  white-space: pre-wrap; /* 保留换行 */
  word-break: break-word; /* 自动换行 */
}

.comment-actions {
  display: flex;
  justify-content: flex-end; /* 操作按钮靠右对齐 */
  align-items: center;
}

.comment-replies {
  margin-top: 15px; /* 回复区域顶部间距 */
}

.comment-input-area {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.comment-submit-button {
  text-align: right;
}

/* 优化评论列表滚动条样式 */
.comment-list::-webkit-scrollbar {
  width: 6px;
}

.comment-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.comment-list::-webkit-scrollbar-track {
  background: #f5f7fa;
}

.comments-loading {
  text-align: center;
  color: #909399;
  margin-top: 20px;
}
/* --- 活动评论样式 --- end */
</style>